package cn.congzhou.crm.web.filter;

import cn.congzhou.crm.utils.ResultJSON;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

@Component("crmFormAuthenticationFilter")
public class CRMFormAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        response.setContentType("text/json;charset=UTF-8");
        String msg="";
        if(e instanceof UnknownAccountException){
            msg="账号不存在";
        }else if(e instanceof IncorrectCredentialsException){
            msg="密码错误";
        }else{
            msg="未知错误";
        }
        //打印登录失败错误信息
        e.printStackTrace();
        ResultJSON result = new ResultJSON();
        result.mark(msg);
        try {
            response.getWriter().print(JSON.toJSONString(result));
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return false;
    }


    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("text/json;charset=UTF-8");
        ResultJSON result = new ResultJSON();
        response.getWriter().print(JSON.toJSONString(result));
        return false;
    }

}

